//
//  MainTableViewController.m
//  HYSmileiOS
//
//  Created by alekye on 16/4/24.
//  Copyright © 2016年 heyou. All rights reserved.
//

#import "MainTableViewController.h"
#import "heyou.h"
#import "ArticleTableViewCell.h"
#import "HYImageBrowser.h"
#import "TestData.h"
//#import "WBDetailViewController.h"
#import "ArticleDetailViewController.h"

@interface MainTableViewController ()

@property (strong, nonatomic) NSArray<ArticleModel*> *mArticleList;

@end

@implementation MainTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [self getDataFromLocal];
    [self getDataFromLocal];
    
    [self setupTableView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- get data
- (void)getDataFromLocal {
    // test test data
    NSArray<ArticleModel*> *tList = [TestData getArticleList];
    self.mArticleList = tList;
}

- (void)getDataFromServer {
    
}

- (void)updateUI {
    [self.tableView reloadData];
}

/**
 *  下拉刷新
 */
- (void)headerRereshing {
    WS(ws);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [ws.tableView reloadData];
        // 调用endRefreshing可以结束刷新状态
        [ws.tableView.mj_header endRefreshing];
    });
}

/**
 *  下拉加载
 */
- (void)footerRefreshing {
    WS(ws);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [ws.tableView reloadData];
        // 调用endRefreshing可以结束刷新状态
        [ws.tableView.mj_footer endRefreshing];
    });
}

#pragma mark - setup tableview
- (void)setupTableView {
    // 注册自定义XIB
    [self.tableView registerXibWithClass:[ArticleTableViewCell class]];
    [self.tableView hy_disableTouchDelay];
    
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRereshing)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefreshing)];
}

#pragma mark - config tableviewcell
/**
 *  根据数据模型配置TableViewCell
 *
 *  @param cell      视图
 *  @param indexPath 索引
 *  @param download  是否下载网络图片
 */
- (void)configTableViewCell:(UITableViewCell*)cell forIndex:(NSIndexPath*)indexPath downloadImage:(BOOL)download{
    ArticleTableViewCell *tCell = (ArticleTableViewCell*)cell;
    ArticleModel *model = [self.mArticleList objectAtIndex:indexPath.section];
    [tCell setArticleInfo:model downloadImage:download];
}

#pragma mark - TableView height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 45.0f;
    
    NSString *identifier = NSStringFromClass([ArticleTableViewCell class]);
    WS(ws);
    height = [tableView fd_heightForCellWithIdentifier:identifier cacheByIndexPath:indexPath configuration:^(id cell) {
        [ws configTableViewCell:cell forIndex:indexPath downloadImage:NO];
    }];
    
    height = MAX(height, 45.0f);
    
    return height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0.0f;
    }
    return 10.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.mArticleList.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}


- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *identifier = NSStringFromClass([ArticleTableViewCell class]);
    ArticleTableViewCell *tCell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    tCell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    WS(ws);
    // 收藏
    [tCell.buttonMark handleControlEvent:UIControlEventTouchUpInside withBlock:^(UIButton *sender) {
        NSLog(@"button mark : {%ld, %ld}", indexPath.section, indexPath.row);
    }];
    // 评论
    [tCell.buttonComment handleControlEvent:UIControlEventTouchUpInside withBlock:^(UIButton *sender) {
        NSLog(@"button comment : {%ld, %ld}", indexPath.section, indexPath.row);
        ArticleModel *model = [ws.mArticleList objectAtIndex:indexPath.section];
        [ws _showArticleDetail:model];
    }];
    // 踩
    [tCell.buttonHate handleControlEvent:UIControlEventTouchUpInside withBlock:^(UIButton *sender) {
        NSLog(@"button hate : {%ld, %ld}", indexPath.section, indexPath.row);
    }];
    // 赞
    [tCell.buttonLike handleControlEvent:UIControlEventTouchUpInside withBlock:^(UIButton *sender) {
        NSLog(@"button like : {%ld, %ld}", indexPath.section, indexPath.row);
    }];
    // 图片 - 单击
    [tCell.imageContent handleSingleTapWithBlock:^{
        NSLog(@"image single tap : {%ld, %ld}", indexPath.section, indexPath.row);
        ArticleModel *model = [self.mArticleList objectAtIndex:indexPath.section];
        NSString *fURL = model.thumbnailUrl;
        BOOL bExist = [[SDImageCache sharedImageCache] diskImageExistsWithKey:fURL];
        if (bExist) {
            HYImageBrowser *browser = [XibUtils loadXib:[HYImageBrowser class]];
            [browser setImage:model cell:tCell inTable:tableView];
            [browser show];
        } else {
            NSLog(@"no image can be browsed");
        }
        
    }];
    
    // Configure the cell...
    [self configTableViewCell:tCell forIndex:indexPath downloadImage:YES];
    
    return tCell;
}

#pragma mark -- goto detail view
- (void)_showArticleDetail:(ArticleModel*)am {
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Home" bundle:nil];
    NSString *identifier = NSStringFromClass([ArticleDetailViewController class]);
    ArticleDetailViewController *vc = [storyBoard instantiateViewControllerWithIdentifier:identifier];
    vc.articleModel = am;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - TableView Delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSLog(@"didSelectRowAtIndexPath : %@", indexPath);
    ArticleModel *model = [self.mArticleList objectAtIndex:indexPath.section];
    [self _showArticleDetail:model];
}

@end
